const express = require('express')
const app = express()

const cors = require('cors')
app.use(cors())

app.use(express.urlencoded({extended: false}))

const expressJWT = require('express-jwt')
const Secret = require('./config')

const user_router = require('./router/user')
const info_router = require('./router/userinfo')

// 设置错误处理函数
app.use((req,res,next)=>{
  res.cc = (err, status = 1)=>{
    res.send({
      status,
      message: err instanceof Error ? err.message : 'err'
    })
  }
  next()
})

// 还原token
app.use(expressJWT({secret: Secret.jwtSecretKey}).unless({path: [/^\/api\//]}))

// 注册user路由
app.use('/api',user_router)
// 注册 userinfo 路由
app.use('/my',info_router)

app.use((err,req,res,next)=>{
  if(err.name === 'UnauthorizedError'){
    return res.cc('无效的Token')
  }
  res.cc(err)
})

app.listen(800,()=>{
  console.log('api server running at http://127.0.0.1:800')
})